package com.comment.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.comment.dto.Result;
import com.comment.dto.UserDTO;
import com.comment.entity.Blog;
import com.comment.entity.Follow;
import com.comment.entity.User;
import com.comment.mapper.BlogMapper;
import com.comment.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.comment.service.IFollowService;
import com.comment.service.IUserService;
import com.comment.utils.SystemConstants;
import com.comment.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Autowired
    private IUserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IFollowService followService;
    /**
     * 查询热门笔记
     *
     * @param current
     * @return
     */
    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
            // 3.查询笔记是否点赞
            String key = "blog:liked:" + blog.getId();
            Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
            blog.setIsLike(score != null);
        });
        return Result.ok(records);
    }

    /**
     * 查询笔记详情
     *
     * @param id
     * @return
     */
    @Override
    public Result queryBlogById(Long id) {
        // 1.查询笔记
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("笔记不存在");
        }
        // 2.查询笔记相关用户
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());

        // 3.查询笔记是否点赞
        String key = "blog:liked:" + id;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score != null);
        // 4.返回笔记详情
        return Result.ok(blog);
    }

    /**
     * 点赞探店笔记
     *
     * @param id
     * @return
     */
    @Override
    public Result likeBlog(Long id) {
        // 1.判断当前登录用户是否已经点赞
        // 1.1.获取当前登录用户
        Long userId = UserHolder.getUser().getId();
        // 1.2.查询当前登录用户是否已经点赞，从Redis的Set集合查看
        String key = "blog:liked:" + id;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        // 2.如果未点赞，可以点赞
        if (score == null) {
            // 2.1.Mysql数据库点赞数据+1 update blog set liked = liked + 1 where id = ?
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
            // 2.2.保存用户点赞数据到Redis的ZSet集合（笔记id为key，userId为value）
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
        } else {
            // 3.如果已点赞，取消点赞
            // 3.1.Mysql数据库点赞数据-1
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
            // 3.2.移除Redis的ZSet集合中的数据
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }
        }
        return Result.ok();
    }

    /**
     * 查询点赞排行榜
     *
     * @param id
     * @return
     */
    @Override
    public Result queryBlogLikes(Long id) {
        // 1.查询top5的点赞用户userId
        Set<String> top5Id = stringRedisTemplate.opsForZSet().range("blog:liked:" + id, 0, 4);
        if (top5Id == null || top5Id.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        // 2.解析查询出的用户userId
        List<Long> ids = top5Id.stream().map(Long::valueOf).collect(Collectors.toList());
        // 3.根据userID查询用户信息
        List<User> users = userService.listByIds(ids);
        List<UserDTO> userDTOS = users.stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());
        return Result.ok(userDTOS);
    }

    /**
     * 发布探店笔记
     *
     * @param blog
     * @return
     */
    @Override
    public Result saveBlog(Blog blog) {
        // 1.获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 2.保存探店笔记
        boolean isSuccess = save(blog);
        if (!isSuccess){
            return Result.fail("新增笔记失败");
        }
        // 3.查询笔记作者的所有粉丝 select * from tb_follow where follow_id = ?
        List<Follow> followIds = followService.query().eq("follow_id", user.getId()).list();
        // 4.推送笔记给所有粉丝
        for (Follow follow : followIds){
            // 4.1.获取粉丝id
            Long userId = follow.getUserId();
            // 4.2.推送，将笔记id放入Redis的zSet集合中，zSet集合的分数使用当前时间戳，作为排序依据
            String key = "feed:" + userId;
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }
        // 5.返回id
        return Result.ok(blog.getId());
    }
}
